'use client'
import { useEffect, useState, useRef } from 'react';
import { v4 as uuidv4 } from 'uuid';
import mammoth from 'mammoth';
import Image from 'next/image';
import liaotianIcon from '@/app/chat/ui/旺旺.png';
import liaotianBlueIcon from '@/app/chat/ui/旺旺blue.png';
import deleteIcon from '@/app/chat/ui/删除.png';
interface Message {
  id: string;
  role: 'user' | 'assistant';
  content: string;
  parts?: { type: string; text: string }[];
  feedback?: 'like' | 'dislike' | null;
  isStreaming?: boolean; // 标记消息是否正在流式输出
}

interface Memory {
  id: string;
  memory: string;
  metadata?: {
    originalMessages?: {
      role: string;
      content: string;
    }[];
    [key: string]: unknown;
  };
  [key: string]: unknown;
}

interface DatabaseRecord {
  id: string;
  vaule: string;
}

export default function Chat() {
  const [input, setInput] = useState('');// 输入框内容
  const [sidebarOpen, setSidebarOpen] = useState(true);// 侧边栏（历史对话）开关
  const [messages, setMessages] = useState<Message[]>([]);// 消息列表（核心数据）
  const [isLoading, setIsLoading] = useState(false);// 发送/加载状态
  const [uploadedFile, setUploadedFile] = useState<File | null>(null);// 上传的文件
  const [fileError, setFileError] = useState<string>('');// 文件上传错误提示
  const fileInputRef = useRef<HTMLInputElement>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 存储 mem0 测试结果
  // const [mem0TestResult, setMem0TestResult] = useState<string>('');
  const [isMem0Testing, setIsMem0Testing] = useState(false);

  // 新增：userId 相关状态
  const [allUserIds, setAllUserIds] = useState<string[]>([]); // 所有 userId
  const [currentUserId, setCurrentUserId] = useState<string>(''); // 当前选中的 userId
  // const [userMemories, setUserMemories] = useState<Memory[]>([]); // 当前 currentUserId 对应的所有 Mem0 原始记忆数据

  // 获取数据库中所有的 userId
  const getAllUserIds = async (): Promise<string[]> => {
    console.log('🔍 开始查询所有 userId...');
    try {
      const response = await fetch('/api/vercel', {
        method: 'GET',
      });
      const result = await response.json();

      if (result.success && result.data && result.data.length > 0) {
        console.log('✅ 数据库查询成功');

        // 提取所有 userId（从 vaule 字段）
        const userIds = result.data.map((record: DatabaseRecord) => record.vaule);
        console.log('📋 所有 userId：', userIds);

        return userIds;
      } else {
        console.warn('⚠️ 数据库查询无数据');
        return [];
      }
    } catch (error) {
      console.error('❌ 数据库查询失败：', error);
      return [];
    }
  };

  // 获取指定用户的所有记忆（只基于 userId）
  const loadUserMemories = async (userId: string): Promise<void> => {
    console.log(`🔍 加载用户 ${userId} 的记忆...`);
    console.log('💡 提示: mem0ai 是异步处理的，刚发送的消息可能需要几秒后才能查到');
    setIsMem0Testing(true);
    try {
      // 调用mem0ai查询到当前id的所有聊天记录
      const response = await fetch('/api/manage/mem0', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          action: 'search',
          data: {
            userId: userId
          }
        })
      });
      const result = await response.json();
      if (result.success) {
        const memories: Memory[] = result.data;
        console.log('📝 获取到的记忆：', memories);

        // 存储记忆到状态
        // setUserMemories(memories);

        // 转换记忆为消息格式并显示
        if (memories && memories.length > 0) {
          const allMessages: Message[] = [];

          // 遍历所有记忆，提取 originalMessages
          memories.forEach((memory, index) => {
            if (memory.metadata && memory.metadata.originalData) {
              const originalData = memory.metadata.originalData;

              originalData.forEach((msg, msgIndex) => {
                allMessages.push({
                  id: `${index}-${msgIndex}`,
                  role: msg.role as 'user' | 'assistant',
                  content: msg.content,
                  parts: [{ type: 'text', text: msg.content }],
                  feedback: null
                });
              });
            }
          });

          // 设置消息列表
          setMessages(allMessages);
          console.log(`✅ 加载了 ${memories.length} 条记忆，共 ${allMessages.length} 条消息`);
        } else {
          setMessages([]);
          console.log('⚠️ 该用户暂无记忆');
        }
      } else {
        console.error(`❌ 获取失败：${result.error}`);
        setMessages([]);
      }
    } catch (error) {
      console.error(`❌ 获取失败：${error instanceof Error ? error.message : '未知错误'}`);
      setMessages([]);
    } finally {
      setIsMem0Testing(false);
    }
  };
  // 切换用户
  const handleSwitchUser = async (userId: string) => {
    if (userId === currentUserId) return;

    // console.log(`🔄 切换到用户：${userId}`);
    setCurrentUserId(userId);
    await loadUserMemories(userId);
  };

  // 删除该用户的所有记忆
  const handleDeleteUser = async (userId: string) => {
    if (!confirm(`确定要删除用户 ${userId} 的所有对话吗？`)) {
      return;
    }
    
    try {
      // 调用数据库删除接口
      const response = await fetch('/api/vercel', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userId })
      });
      const result = await response.json();
      
      if (result.success) {
        console.log('✅ 删除成功');
        await fetch('/api/manage/mem0', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            action: 'delete',
            data: {
              userId: userId
            }
          })
        });       
        // 从用户列表中移除
        const newUserIds = allUserIds.filter(id => id !== userId);
        setAllUserIds(newUserIds);
        // 如果删除的是当前用户，切换到第一个用户
        if (userId === currentUserId) {
          if (newUserIds.length > 0) {
            const newUserId = newUserIds[0];
            setCurrentUserId(newUserId);
            await loadUserMemories(newUserId);
          } else {
            // 没有用户了，清空消息
            setCurrentUserId('');
            setMessages([]);
          }
        }
        
        alert('删除成功！');
      } else {
        console.error('❌ 删除失败：', result.error);
        alert(`删除失败：${result.error}`);
      }
    } catch (error) {
      console.error('❌ 删除失败：', error);
      alert(`删除失败：${error instanceof Error ? error.message : '未知错误'}`);
    }
  };

  // 测试添加对话记忆
  const testAddMemory = async (userId: string) => {
    console.log('📝 开始添加对话记忆...');
    try {
      const response = await fetch('/api/manage/mem0', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          action: 'add',
          data: {
            messages: [
              { role: "user", content: "Hi, I'm Alex. I'm a vegetarian and I'm allergic to nuts." },
              { role: "assistant", content: "Hello Alex! I see that you're a vegetarian with a nut allergy." }
            ],
            userId: userId
          }
        })
      });
      const result = await response.json();
      console.log('✅ 添加记忆结果：', result);
      return result;
    } catch (error) {
      console.error('❌ 添加记忆失败：', error);
      return null;
    }
  };

  useEffect(() => {
    // 初始化加载所有 userId
    const initializeUsers = async () => {
      console.log('🚀 初始化用户列表...');

      // 步骤1：获取所有 userId
      const userIds = await getAllUserIds();

      if (userIds.length > 0) {
        setAllUserIds(userIds);

        // 默认选择第一个 userId
        const firstUserId = userIds[0];
        setCurrentUserId(firstUserId);

        console.log(`📌 默认选中用户：${firstUserId}`);

        // 步骤2：加载第一个用户的记忆
        await loadUserMemories(firstUserId);
        // await testAddMemory(firstUserId);
      } else {
        console.log('⚠️ 未找到任何用户');
      }

      console.log('🔚 初始化完成。');
    };

    // 调用初始化函数
    initializeUsers();
  }, []); // <-- 空的依赖数组是关键


  // 自动滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };
  // 从随机生成 sessionId
  const [sessionId] = useState(() => { return uuidv4() });// 会话ID（唯一标识当前对话）
  useEffect(() => {
    // 将 sessionId 保存到本地存储，以便页面刷新后仍能复用
    localStorage.setItem('chat-session-id', sessionId);
  }, [sessionId]);
  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  // 处理文件选择
  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    setFileError('');

    if (!file) return;

    // 文件大小限制：10MB
    const maxSize = 20 * 1024 * 1024;
    if (file.size > maxSize) {
      setFileError('文件大小不能超过20MB');
      return;
    }

    // 支持的文件类型验证
    const fileExtension = file.name.split('.').pop()?.toLowerCase();
    const allowedExtensions = ['txt', 'md', 'doc', 'docx'];

    if (!allowedExtensions.includes(fileExtension || '')) {
      setFileError('仅支持 .txt, .md, .doc, .docx 格式的文件');
      return;
    }

    setUploadedFile(file);
  };

  // 触发文件选择
  const handleFileButtonClick = () => {
    fileInputRef.current?.click();
  };

  // 移除文件
  const handleRemoveFile = () => {
    setUploadedFile(null);
    setFileError('');
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  // 处理消息反馈（点赞/点踩）
  const handleFeedback = (messageId: string, feedbackType: 'like' | 'dislike') => {
    setMessages(prev => prev.map(msg => {
      if (msg.id === messageId) {
        // 如果已经有反馈了，不允许再次修改
        if (msg.feedback !== null && msg.feedback !== undefined) {
          return msg;
        }
        // 设置反馈
        return { ...msg, feedback: feedbackType };
      }
      return msg;
    }));

    // 这里可以将反馈数据发送到后端进行保存
    console.log(`消息 ${messageId} 收到反馈: ${feedbackType}`);
  };

  // 根据文件类型读取文件内容
  const readFileContent = async (file: File): Promise<string> => {
    const fileExtension = file.name.split('.').pop()?.toLowerCase();

    try {
      switch (fileExtension) {
        case 'txt':
        case 'md':
          // 纯文本文件直接读取
          return await file.text();

        case 'docx':
          // 使用mammoth解析.docx文件
          const arrayBuffer = await file.arrayBuffer();
          const result = await mammoth.extractRawText({ arrayBuffer });
          return result.value;

        case 'doc':
          // .doc格式需要服务端处理，这里提示用户
          throw new Error('.doc 格式较老，建议转换为 .docx 格式后上传');

        default:
          throw new Error('不支持的文件格式');
      }
    } catch (error) {
      console.error('读取文件失败:', error);
      throw error;
    }
  };

  // 提交至模型
  const sendMessage = async (text: string) => {
    if (!text.trim() || isLoading) return;

    // 添加用户消息
    const userMessage: Message = {
      id: Date.now().toString(),
      role: 'user',
      content: text,
      parts: [{ type: 'text', text }]
    };

    // 将用户之前信息和现在信息拼接起来 传给大模型
    setMessages(prev => [...prev, userMessage]);
    setIsLoading(true);

    try {
      // 如果有上传文件，读取文件内容
      let fileContent = null;
      if (uploadedFile) {
        try {
          fileContent = await readFileContent(uploadedFile);
        } catch (error) {
          console.error('文件读取失败:', error);
          setFileError(error instanceof Error ? error.message : '文件读取失败');
          setIsLoading(false);
          return;
        }
      }

      const response = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-Session-ID': sessionId },
        body: JSON.stringify({
          uploadedDocument: fileContent ? {
            content: fileContent,
            filename: uploadedFile?.name || 'uploaded.txt'
          } : null,
          messages: [...messages, userMessage].map(m => ({
            role: m.role,
            content: m.content,
            parts: m.parts
          }))
        })
      });

      if (!response.ok) throw new Error('请求失败');

      // 处理流式响应
      const reader = response.body?.getReader();
      const decoder = new TextDecoder();
      let assistantText = '';

      // 创建助手消息
      const assistantId = (Date.now() + 1).toString();
      // 创造助手信息
      setMessages(prev => [...prev, {
        id: assistantId,
        role: 'assistant',
        content: '',
        parts: [{ type: 'text', text: '' }],
        feedback: null,
        isStreaming: true // 开始流式输出
      }]);

      while (reader) {
        const { done, value } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value, { stream: true });
        const lines = chunk.split('\n');

        for (const line of lines) {
          if (line.trim() && line.startsWith('0:')) {
            try {
              const text = JSON.parse(line.slice(2));
              assistantText += text;
              // 更新助手消息，保持 isStreaming: true
              setMessages(prev => prev.map(msg =>
                msg.id === assistantId
                  ? { ...msg, content: assistantText, parts: [{ type: 'text', text: assistantText }], isStreaming: true }
                  : msg
              ));
            } catch (e) {
              console.error('解析流式数据失败:', e, '原始数据:', line);
            }
          }
        }
      }

      // 流式输出完成，设置 isStreaming: false
      setMessages(prev => prev.map(msg =>
        msg.id === assistantId
          ? { ...msg, isStreaming: false }
          : msg
      ));

      // 保存对话到 mem0ai
      if (currentUserId && assistantText) {
        try {
          console.log('💾 保存对话到 mem0ai...');
          console.log('📌 当前 userId:', currentUserId);
          
          const saveResponse = await fetch('/api/manage/mem0', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              action: 'add',
              data: {
                messages: [
                  { role: 'user', content: text },
                  { role: 'assistant', content: assistantText }
                ],
                userId: currentUserId
              }
            })
          });
          
          const saveResult = await saveResponse.json();
          
          if (saveResult.success) {
            console.log('✅ 对话已提交到 mem0ai (状态: PENDING，后台处理中)');
            console.log('⏳ mem0ai 正在后台处理记忆，可能需要几秒钟...');
          } else {
            console.error('❌ 保存失败:', saveResult.error);
          }
        } catch (error) {
          console.error('⚠️ 保存对话失败（不影响聊天）:', error);
        }
      }
    } catch (error) {
      console.error('发送消息失败:', error);
      // 添加错误消息
      setMessages(prev => [...prev, {
        id: (Date.now() + 1).toString(),
        role: 'assistant',
        content: '抱歉，发生了错误，请稍后重试。',
        parts: [{ type: 'text', text: '抱歉，发生了错误，请稍后重试。' }],
        feedback: null,
        isStreaming: false // 错误消息不是流式输出
      }]);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="flex h-screen bg-gray-50 dark:bg-gray-900">
      {/* 左侧边栏 - 历史对话 */}
      <aside
        className={`${sidebarOpen ? 'w-64' : 'w-0'
          } transition-all duration-300 bg-white dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700 flex flex-col overflow-hidden`}
      >
        {/* 标题区域 */}
        <div className="p-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
          <h2 className="text-lg font-semibold text-gray-800 dark:text-white">历史对话</h2>
          <button
            onClick={() => setMessages([])}
            className="text-sm text-blue-500 hover:text-blue-600 transition-colors"
          >
            + 新对话
          </button>
        </div>

        {/* 用户列表 */}
        <nav className="flex-1 overflow-y-auto py-2" style={{ padding: '0.7rem 0.2rem' }}>
          {allUserIds.length > 0 ? (
            <div className="space-y-2">
              {allUserIds.map((userId) => (
                <div
                  key={userId}
                  className={`flex items-center justify-between transition-all cursor-pointer ${currentUserId === userId ? 'rounded-l-3xl' : ''
                    }`}
                  style={{
                    backgroundColor: currentUserId === userId ? '#f6f6ff' : 'transparent',
                    color: currentUserId === userId ? '#7781fc' : 'inherit',
                    marginBottom: '10px'
                  }}
                  onClick={() => handleSwitchUser(userId)}
                >
                  <div className="flex items-center flex-1 px-3 py-3">
                    {/* 对话图标 - 根据选中状态切换图片 */}
                    <div className={`${currentUserId === userId ? 'w-5 h-5' : 'w-[18px] h-[18px]'} mr-2 flex-shrink-0`}>
                      <Image
                        src={currentUserId === userId ? liaotianBlueIcon : liaotianIcon}
                        alt="chat icon"
                        width={currentUserId === userId ? 20 : 18}
                        height={currentUserId === userId ? 20 : 18}
                        className="object-contain"
                      />
                    </div>

                    {/* 用户名 */}
                    <span
                      className={`${currentUserId === userId ? 'text-sm font-medium' : 'text-[13px]'
                        } truncate`}
                      style={{
                        fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',
                        color: currentUserId === userId ? '#000' : 'inherit'
                      }}
                    >
                      {userId}
                    </span>
                  </div>

                    {/* 删除按钮（仅在选中时显示） */}
                    {currentUserId === userId && (
                      <div className="mr-3 flex-shrink-0">
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            handleDeleteUser(userId);
                          }}
                          className="opacity-70 hover:opacity-100 transition-opacity"
                          title="删除该用户的所有对话"
                        >
                          <Image
                            src={deleteIcon}
                            alt="delete"
                            width={18}
                            height={18}
                            className="object-contain"
                          />
                        </button>
                      </div>
                    )}
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center text-gray-400 dark:text-gray-500 text-sm py-8">
              暂无用户数据
            </div>
          )}
        </nav>

        {/* 底部信息 */}
        <div className="p-4 border-t border-gray-200 dark:border-gray-700">
          <div className="text-xs text-gray-500 dark:text-gray-400">
            💡 点击用户查看对话记忆
          </div>
          {currentUserId && (
            <div className="text-xs mt-1" style={{ color: '#5662f6' }}>
              当前：{currentUserId}
            </div>
          )}
        </div>
      </aside>

      {/* 主聊天区域 */}
      <div className="flex-1 flex flex-col">
        {/* 顶部栏 */}
        <header className="border-b border-gray-200 dark:border-gray-700 px-6 py-4 flex items-center justify-between">
          <div className="flex items-center space-x-4">
            <button
              onClick={() => setSidebarOpen(!sidebarOpen)}
              className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
            >
              <svg className="w-5 h-5 text-gray-600 dark:text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
              </svg>
            </button>
            <h1 className="text-xl font-semibold text-gray-800 dark:text-white">
              🤖 智能助手
            </h1>
          </div>
          <button
            onClick={() => setMessages([])}
            className="px-4 py-2 text-sm bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
          >
            清空对话
          </button>
        </header>

        {/* 消息列表区域 */}
        <div className="flex-1 overflow-y-auto px-6 py-8">
          <div className="max-w-3xl mx-auto space-y-6">
            {messages.length === 0 && (
              <div className="text-center py-12">
                <div className="text-6xl mb-4">🤖</div>
                <h3 className="text-xl font-medium text-gray-800 dark:text-white mb-2">
                  开始对话吧
                </h3>
                <p className="text-gray-500 dark:text-gray-400">
                  我会自动识别你的问题类型，为你提供最合适的答案
                </p>
              </div>
            )}

            {messages.map(message => (
              <div
                key={message.id}
                className={`flex ${message.role === 'user' ? 'justify-end' : 'justify-start'}`}
              >
                <div className={`max-w-[75%] ${message.role === 'assistant' ? 'space-y-2' : ''}`}>
                  <div
                    className={`rounded-2xl px-4 py-3 ${message.role === 'user'
                      ? 'bg-blue-500 text-white'
                      : 'bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200 border border-gray-200 dark:border-gray-700'
                      }`}
                  >
                    {message.parts?.map((part, i) => {
                      if (part.type === 'text') {
                        return (
                          <p key={i} className="text-sm whitespace-pre-wrap break-words leading-relaxed">
                            {part.text}
                          </p>
                        );
                      }
                      return null;
                    })}
                  </div>

                  {/* 反馈按钮 - 仅在 assistant 消息完成后且有内容时显示 */}
                  {message.role === 'assistant' && message.content && !message.isStreaming && (
                    <div className="flex items-center gap-2 px-2">
                      {/* 点赞按钮 */}
                      <button
                        onClick={() => handleFeedback(message.id, 'like')}
                        disabled={message.feedback !== null && message.feedback !== undefined}
                        className={`group flex items-center gap-1 px-2 py-1 rounded-lg transition-all ${message.feedback === 'like'
                          ? 'bg-green-100 dark:bg-green-900/30 text-green-600 dark:text-green-400'
                          : message.feedback === 'dislike'
                            ? 'opacity-40 cursor-not-allowed text-gray-400 dark:text-gray-500'
                            : 'hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-500 dark:text-gray-400 cursor-pointer'
                          }`}
                        title={message.feedback !== null && message.feedback !== undefined ? '已反馈' : '满意'}
                      >
                        <svg
                          className="w-4 h-4"
                          fill={message.feedback === 'like' ? 'currentColor' : 'none'}
                          stroke="currentColor"
                          viewBox="0 0 24 24"
                        >
                          <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            strokeWidth={2}
                            d="M14 10h4.764a2 2 0 011.789 2.894l-3.5 7A2 2 0 0115.263 21h-4.017c-.163 0-.326-.02-.485-.06L7 20m7-10V5a2 2 0 00-2-2h-.095c-.5 0-.905.405-.905.905 0 .714-.211 1.412-.608 2.006L7 11v9m7-10h-2M7 20H5a2 2 0 01-2-2v-6a2 2 0 012-2h2.5"
                          />
                        </svg>
                        <span className="text-xs">{message.feedback === 'like' ? '已点赞' : '满意'}</span>
                      </button>
                      {/* 点踩功能 */}
                      <button
                        onClick={() => handleFeedback(message.id, 'dislike')}
                        disabled={message.feedback !== null && message.feedback !== undefined}
                        className={`group flex items-center gap-1 px-2 py-1 rounded-lg transition-all ${message.feedback === 'dislike'
                          ? 'bg-red-100 dark:bg-red-900/30 text-red-600 dark:text-red-400'
                          : message.feedback === 'like'
                            ? 'opacity-40 cursor-not-allowed text-gray-400 dark:text-gray-500'
                            : 'hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-500 dark:text-gray-400 cursor-pointer'
                          }`}
                        title={message.feedback !== null && message.feedback !== undefined ? '已反馈' : '不满意'}
                      >
                        <svg
                          className="w-4 h-4"
                          fill={message.feedback === 'dislike' ? 'currentColor' : 'none'}
                          stroke="currentColor"
                          viewBox="0 0 24 24"
                        >
                          <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            strokeWidth={2}
                            d="M10 14H5.236a2 2 0 01-1.789-2.894l3.5-7A2 2 0 018.736 3h4.018a2 2 0 01.485.06l3.76.94m-7 10v5a2 2 0 002 2h.096c.5 0 .905-.405.905-.904 0-.715.211-1.413.608-2.008L17 13V4m-7 10h2m5-10h2a2 2 0 012 2v6a2 2 0 01-2 2h-2.5"
                          />
                        </svg>
                        <span className="text-xs">{message.feedback === 'dislike' ? '已点踩' : '不满意'}</span>
                      </button>
                    </div>
                  )}
                </div>
              </div>
            ))}

            {isLoading && (
              <div className="flex justify-start">
                <div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-2xl px-4 py-3">
                  <div className="flex space-x-2">
                    <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0ms' }}></div>
                    <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '150ms' }}></div>
                    <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '300ms' }}></div>
                  </div>
                </div>
              </div>
            )}
            <div ref={messagesEndRef} />
          </div>
        </div>

        {/* 输入框区域 */}
        <div className="px-6 pb-8">
          <div className="max-w-3xl mx-auto">
            {/* 文件错误提示 */}
            {fileError && (
              <div className="mb-2 bg-red-50 dark:bg-red-900/20 px-3 py-2 rounded text-sm">
                <span className="text-red-600 dark:text-red-400">
                  ⚠️ {fileError}
                </span>
              </div>
            )}

            {/* 文件上传提示 */}
            {uploadedFile && !fileError && (
              <div className="mb-2 flex items-center justify-between bg-blue-50 dark:bg-blue-900/20 px-3 py-2 rounded text-sm">
                <span className="text-blue-600 dark:text-blue-400">
                  📎 {uploadedFile.name} ({(uploadedFile.size / 1024).toFixed(2)} KB)
                </span>
                <button
                  type="button"
                  onClick={handleRemoveFile}
                  className="text-red-500 hover:text-red-600 ml-2"
                >
                  ✕
                </button>
              </div>
            )}

            <form
              onSubmit={e => {
                e.preventDefault();
                if (input.trim()) {
                  sendMessage(input);
                  setInput('');
                }
              }}
              className="relative"
            >
              <input
                className="w-full px-4 py-2 pr-12 dark:bg-zinc-900 border border-zinc-300 dark:border-zinc-800 rounded shadow-xl focus:outline-none focus:border-blue-500 transition-colors"
                value={input}
                placeholder="输入你的问题..."
                onChange={e => setInput(e.currentTarget.value)}
                disabled={isLoading}
              />

              {/* 文件上传按钮 */}
              <input
                ref={fileInputRef}
                type="file"
                accept=".txt,.md,.doc,.docx"
                onChange={handleFileChange}
                className="hidden"
              />
              <button
                type="button"
                onClick={handleFileButtonClick}
                disabled={isLoading}
                className="absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-500 hover:text-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                title="上传文档"
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" />
                </svg>
              </button>
            </form>
          </div>
        </div>
      </div>
    </div>
  );
}
